// web proxy
// This example demonstrates the basic usage of mobileProcessing
// to relay information received from the phone serial port to a website and back

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.*;

String appname  = "iDenTest_g";

PFont font;
String ports;          // port used for io from the phone - usually COM0
String rmessage;       // info received from the arduino; payload
//byte[] smessage;       // data received from web
String statusmsg = "welcome, press a key to start";  // process updates on screen for debugging
String connmsg = "no serial ports";       // serial connectivity msgs

int endbyte = 35;         //# end of serial data -> carriage return 10

// data received from the controller
String domain = "none";         // domain info for gprs connection
String path = "none";           // file path on server starting with a /
String querystring;

// IO 
InputStream m_is;
OutputStream m_os;
CommConnection cc;

// net
PClient client;
PRequest request;

void setup() { 
  noLoop();
  font = loadFont(FACE_SYSTEM, STYLE_PLAIN, SIZE_SMALL);
  textFont(font);
  ports = System.getProperty("microedition.commports");

  if (ports!=null ) { //create connection (can do in setup()?)
    try {
      // the speed of the connection may have to change to match that of your phone.
      cc = (CommConnection) Connector.open("comm:COM0;baudrate=9600;autocts=off;autorts=off",Connector.READ_WRITE,true); 
      m_is  = cc.openInputStream();
      m_os = cc.openOutputStream();     
      connmsg = "Connected: " +  ports;
    }
    catch( Throwable t ) {
      connmsg = "serialopen:" + t;  
    }
    writeSerialMsg( appname+"\n" );  // say hello
} 

  //redraw();
  //getserialdata();
  //writeToSerial( "\n".getBytes() );  // also starts reading
}


// screen layout is:
// version 
// 
//
void draw() {
  background(155);
  fill(0);

  text( connmsg,   0, 10,          width, 30);
  text( statusmsg, 0, 40,          width, 30);   
  text( appname,   0, height-12,   width, 20);

}


// app will only start when users presses any key
void keyPressed() {
  getserialdata();
}


void getserialdata() {
  try { 
    //wait on the serial for data until we get the endbyte
    int ch = 0;                 // null char
    rmessage = "";
    while(ch !=endbyte ) {
      if (m_is.available() > 0) {
        ch = m_is.read();
        if (ch != endbyte) {
          rmessage = rmessage + (char) ch; // append data each char received to build the query string
        }
      }
    }
    statusmsg = rmessage;
    redraw();
    sendWebData(rmessage);  // call the web get routine
  }  
  // catch any errors
  catch( Throwable t ) {
    statusmsg = "getserialdata:" + t;	
    redraw();
  }
}


// append data collected from serial to the query string & send the GET request
void sendWebData (String args) {
  String info[]  = split(args,",");

  if (info.length >= 2) {
    domain = info[0];
    path   = info[1];
    querystring = "?";
    if (info.length == 3) {
      // this means we are sending something to the website
      querystring = "?" + info[2];
    } 
  }

  client = new PClient(this, domain);
  request = client.GET(path + querystring); 
}


// the web library will generate events that will be caught and handled by the cases below
void libraryEvent(Object library, int event, Object data) {
  if (library == request) {
    if (event == PRequest.EVENT_CONNECTED) {
      // connected, start reading the data
      request.readBytes();
      statusmsg = "Fetching. . .";	
      redraw();

    } 
    else if (event == PRequest.EVENT_DONE) {
      // done reading
      byte[] smessage = (byte[]) data;
      request.close();
      statusmsg = "Got data!";	
      redraw();

      // pipe data received down the serial port
      writeToSerial(smessage); 
    } 
    else if (event == PRequest.EVENT_ERROR) {
      // an error occurred, get the error message
      statusmsg = (String) data;
      redraw();
    }
  }
}

void writeToSerial(byte[] smessage) {
  try {
    m_os.write(smessage);     //write the message bytes
    // go back to listen for more data on the serial port
    getserialdata();
  }
  catch( Throwable t ) {
    statusmsg = "writeSerial: " + t;
    redraw();	
  }
}

void writeSerialMsg(String msg) {
  try {
    m_os.write(msg.getBytes());     //write the message bytes
  }
  catch( Throwable t ) {
    statusmsg = "Error: " + t;
    redraw();	
  }  
}





